let baseURL = "http://10.5.80.109:10000/api";


export const http = async (url, data) => {
    var xhr = new plus.net.XMLHttpRequest();
  
    //网络请求开始
    xhr.onloadstart = function (e) {
        console.log('请求开始：', e);
      
    };
    xhr.onreadystatechange = function () {
      switch ( xhr.readyState ) {
          case 0:
              console.log( "xhr请求已初始化" );
          break;
          case 1:
              console.log( "xhr请求已打开" );
          break;
          case 2:
              console.log( "xhr请求已发送" );
          break;
          case 3:
              console.log( "xhr请求已响应");
              break;
          case 4:
              if ( xhr.status == 200 ) {
                  console.log( "xhr请求成功：",xhr.responseText );
              } else {
                  console.log( "xhr请求失败：",xhr.readyState );
              }
              break;
          default :
              break;
      }
  }

    // 监听下载进度
    xhr.onprogress = function (event) {
        console.log('下载进度：', event.target.responseText);
    };
  
    // 处理请求完成
    xhr.onload = function (e) {
      console.log('请求完成：', e);
    };
    //
  
    // 处理请求错误
    xhr.onerror = function () {
      console.error('Network error occurred'); // 网络错误
    };
  
    // 初始化请求
    xhr.open('POST', baseURL+url, true);
    xhr.setRequestHeader('Content-Type', 'application/json'); // 根据需要设置请求头
    xhr.setRequestHeader('Authorization', uni.getStorageSync("token") && url != "/account/phoneLogin" ? uni.getStorageSync("token") : ""); // 设置请求头中的 token
    xhr.responseType = 'text'; // 设置响应类型为 JSON
  
    // 发送请求，将数据转换为 JSON 字符串
    xhr.send(JSON.stringify(data));
}


export const sendPostRequest = (url, data) => {
    
  var okhttp = plus.android.importClass("okhttp3.OkHttpClient");
  var requestBody = plus.android.importClass("okhttp3.RequestBody");
  var mediaType = plus.android.importClass("okhttp3.MediaType");
  var request = plus.android.importClass("okhttp3.Request");
  var callback = plus.android.implements("okhttp3.Callback", {
    "onFailure": function (call, e) {
      console.error("网络请求失败：" + e.getMessage());
    },
    "onResponse": function (call, response) {
      if (response.isSuccessful()) {
        var responseStr = response.body().string();
        console.log("网络请求成功：" + responseStr);
      } else {
        console.error("网络请求失败：" + response.code() + " " + response.message());
      }
    }
  });

  var urlStr = baseURL + url;
  var client = new okhttp();
  console.log("client", client)
  var requestBody1 = requestBody.create(mediaType.parse("application/json; charset=utf-8"), JSON.stringify(data));
  console.log("requestBody", requestBody1)
  var request1 = new request.Builder().url(urlStr).post(requestBody1).build();
  console.log("request", request1)
  console.log("client", client)
  var call = client.newCall(request1);
  console.log("call", call)
  
  var response = call.enqueue(callback);
}
